// 云函数：userExists —— 仅检测是否存在用户，不创建、不修改
const cloud = require('wx-server-sdk');

cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV });
const db = cloud.database();
const users = db.collection('users');

exports.main = async (event, context) => {
  const { OPENID: openid } = cloud.getWXContext();

  if (!openid) {
    return { code: 500, msg: '获取用户OpenID失败' };
  }

  try {
    const res = await users.where({ _openid: openid }).limit(1).get();
    if (!res.data || res.data.length === 0) {
      return {
        code: 0,
        msg: '用户不存在',
        data: { exists: false, authorized: false }
      };
    }

    const user = res.data[0];
    const authorized = !!(user.authorized && user.nickName && user.avatarUrl);

    return {
      code: 0,
      msg: '查询成功',
      data: {
        exists: true,
        authorized,
        userInfo: authorized ? user : null
      }
    };
  } catch (error) {
    console.error('userExists error:', error);
    return { code: 500, msg: '服务器内部错误', error: error.message };
  }
};